package com.ajhlp.app.phoneDetailQuery.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.ajhlp.app.phoneDetailQuery.controller.RuleConfigController;
import com.ajhlp.app.phoneDetailQuery.model.ConfigurationNameEnum;
import com.ajhlp.app.phoneDetailQuery.rule.Rule;

public class PhoneNumMatchRuleThread implements Runnable {
	
	private Logger log = Logger.getLogger(getClass());
	
	private PhoneNumMatchRuleService matchRuleService;
	
	private StringBuffer matchResult = new StringBuffer();
	
	private List<String> phoneNums;
	
	private RuleConfigController controller;
	
	private String fileName;
	
	public PhoneNumMatchRuleThread(RuleConfigController controller,PhoneNumMatchRuleService matchRuleService,List<String> mobile, String fileName){
		this.matchRuleService = matchRuleService;
		this.phoneNums = mobile;
		this.controller = controller;
		this.fileName = fileName;
	}

	public void run() {
		// TODO Auto-generated method stub
		File target = new File(IConfigModifyService.configProperties.get(ConfigurationNameEnum.SAVE_PATH.getName()) + "match" + File.separator + fileName);
		
		if(!target.getParentFile().exists() && !target.getParentFile().mkdirs()){
			log.warn("创建匹配结果保存文件夹失败");
			controller.onMatch(false, "100%", false, "创建匹配结果保存文件夹失败");
			return;
		}
		
		Rule tmp = null;
		for(int i=0;i<phoneNums.size();i++){
			tmp = matchRuleService.match(phoneNums.get(i));
			if(tmp == null){
				matchResult.append(phoneNums.get(i) + ",未知,未知,未知,0\r\n" );
			}else{
				matchResult.append(phoneNums.get(i) + "," + tmp.getComment() + "," + tmp.getRule() + "," + tmp.getAlias() + "," + tmp.getPrice() + "\r\n" );
			}
			
			if(matchResult.length() > 1000){
				try {
					FileUtils.write(target, matchResult, "UTF-8", true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error("写入匹配结果发生异常",e);
				} finally {
					matchResult.delete(0, matchResult.length());
				}
			}
			try {
				FileUtils.write(target, matchResult, "UTF-8", true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("写入匹配结果发生异常",e);
			} finally {
				matchResult.delete(0, matchResult.length());
			}
			
			controller.onMatch(true, "50%", true, "");
		}
		controller.onMatch(false, "100%", true, "");
		
	}
	
}
